<?php

App::import('Model', 'Expense');
App::import('Model', 'Building');
App::import('Model', 'RefinancingSystem');

class Installment extends AppModel {
	var $name = 'Installment';
	var $primaryKey = 'installment_id';
	//The Associations below have been created with all possible keys, those that are not needed can be removed

	var $belongsTo = array(
		'RefinancingPlan' => array(
			'className' => 'RefinancingPlan',
			'foreignKey' => 'refinancing_plan_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'MoratoriumRefinancingPlan' => array(
			'className' => 'RefinancingPlan',
			'foreignKey' => 'moratorium_refinancing_plan_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

	// Retorna el building id asociado al plan, por medio de la expensa
	function getBuildingId($data)
	{
		$expen = new Expense;
        $info  = $expen->find('all', array('conditions' => array('Expense.refinancing_plan_id'
                                                        => $data['Installment']['refinancing_plan_id']))
                                          );
        $build_id = $info[0]["Property"]["building_id"];  
		return $build_id;
	}

	function getRefSysInfo($id)
	{
		$refin_system = new RefinancingSystem;
        $info  = $refin_system->find('all', array('conditions' => array('RefinancingSystem.refinancing_system_id'
                                                               => $id))
								    );
		$data["amortizacion_system"] = $info[0]["AmortizationSystem"]["meaning"];
		$data["anual_rate"]          = $info[0]["RefinancingSystem"]["annual_rate"];
		return $data;
	}
    
	function getInstallmentFinantialInformation($data){ 
		$expen = new Expense;
		//Leo el building_id del plan asociado a la expensa
		$build_id   = $this->getBuildingId($data);
		//Me traigo el anual rate y el meaning del amortizacion system
		$ref_sys    = $this->getRefSysInfo($build_id);
		$anual_rate = $ref_sys["anual_rate"];
		$amort_sys  = $ref_sys["amortizacion_system"];
		$building = new Building(); 
		$building_data = $building->read(null,$build_id); 
		$payment_data = $building_data["PaymentDue"]; 
		$interest_scheme = $expen->getBuildingInterestScheme($payment_data); 
		
		$installFinantialInfo = array(); 
		$installFinantialInfo["amount"] = round($data["Installment"]["amount"],2); 
		$installFinantialInfo["previous_debt"] = round($data["Installment"]["previous_debt"],2); 
		$installFinantialInfo["payment_amount"] = round($data["Installment"]["payment_amount"],2); 
		$installFinantialInfo["interest(%)"] = ( ($anual_rate /365 ) * 100 ); 
		$installFinantialInfo["next_month_interests"] = 0; 
		$installFinantialInfo['month_new_interests'] = 0;

		// Controlo vencimientos 
		$first_due = $expen->getFirstDueDate($payment_data); 
		$first_gap = $expen->gapDates($first_due); 
		$second_due = $expen->getSecondDueDate($payment_data); 
		$second_gap = $expen->gapDates($second_due); 
		$overdue_gap = 0; 
		// Controlo primer vencimiento 
		if (($first_gap > 0) && ($interest_scheme != "SECOND_DUE_DATE")) { 
			//Controlo segundo vencimiento 
			$overdue_gap = $first_gap; 
		} 
		else if (($first_gap > 0) && ($interest_scheme == "SECOND_DUE_DATE")){ 
			$installFinantialInfo["amount"] = round($data["Installment"]["second_due_amount"],2); 
			if ($second_gap > 0){
				$overdue_gap = $second_gap;
			}
		}
		// El propietario pudo haber pagado parcialmente, y no todo va al interes
		$amount_interest = 0;
		$debt = $installFinantialInfo["amount"] + $data["Installment"]["interest"] + $data["Installment"]["previous_debt"] -        $data["Installment"]["payment_amount"];
		$amount_debt = min($debt,$installFinantialInfo["amount"]);
		$amount_interest = $amount_debt*$overdue_gap*$expen->getBuildingDailyRate($payment_data);
		
		// Intereses de deuda previa
		$previous_debt = $data["Installment"]["interest"] + $data["Installment"]["previous_debt"] - 
                         $data["Installment"]["payment_amount"];
		$previous_debt_amount = min($previous_debt, $data["Installment"]["previous_debt"]);
		$previous_debt_interests = 0;
		if ($previous_debt_amount > 0){
			$previous_debt_interests = $previous_debt_amount*(date("j")-1)*$expen->getBuildingDailyRate($build_id);
		}
        if ($interest_scheme == "DEFERRED") {
            $installFinantialInfo['next_month_interests'] = $amount_interest+$previous_debt_interests;
            $installFinantialInfo['interests'] = round($data['Installment']['interest'],2);    
        }   
        else {
            $installFinantialInfo['month_new_interests'] = $amount_interest+$previous_debt_interests;
            $installFinantialInfo['interests'] = round($data['Installment']['interest']
                                                       +$amount_interest+$previous_debt_interests,2);     
 	    }   
	
		$installFinantialInfo["debt"] = round($installFinantialInfo["amount"] + $installFinantialInfo["previous_debt"] 
                                              + $installFinantialInfo["interests"] 
                                              - $installFinantialInfo["payment_amount"],2);
	
		$installFinantialInfo['interests_debt'] = max(0,$installFinantialInfo['interests'] -  $installFinantialInfo['payment_amount']);
$installFinantialInfo['amount_debt'] = max(0,$installFinantialInfo['interests'] +                                    $installFinantialInfo['previous_debt'] - $installFinantialInfo['payment_amount']);
        $installFinantialInfo['installment_debt'] = max(0,$installFinantialInfo['interests'] + $installFinantialInfo['previous_debt'] + $installFinantialInfo['amount'] - $installFinantialInfo['payment_amount']);;
		return $installFinantialInfo;
	}

}
?>
